//
//  LJYNativePagePlugin.swift
//  ljy_demo
//
//  Created by xiandao on 2025/9/4.
//

import UIKit
import Flutter

class LJYNativePagePlugin: NSObject {
    let PAGE_CHANNEL_NAME = "native_page_channel"
    
    private static var pageChannel: FlutterMethodChannel?
    
    func register(controller : FlutterViewController) {
        LJYNativePagePlugin.pageChannel = FlutterMethodChannel(name: PAGE_CHANNEL_NAME, binaryMessenger: controller.binaryMessenger)
        LJYNativePagePlugin.pageChannel?.setMethodCallHandler({ call, result in
            
            print("----方法名：\(call.method)")
            
            if call.method == "getMeasurementUnit" {
                result("METRIC")
                
                DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                    var dict = [String: Any]()
                    dict.updateValue(222222, forKey: "number")
                    dict.updateValue("仙道是无敌的", forKey: "massage")
                    dict.updateValue(false, forKey: "isTrue")
                    
                    if let chanel = LJYNativePagePlugin.pageChannel {
                        chanel.invokeMethod("xiandao", arguments: self.dictToString(dict))
                    }
                }
            }
        })
    }
    
    // 字典转json
    func dictToString(_ dic:[String : Any]) -> String {
        let data = try? JSONSerialization.data(withJSONObject: dic, options: [])
        let str = String(data: data!, encoding: String.Encoding.utf8)
        return str! as String
    }
}
